package com.brin.core.web;

import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

public class FrameworkDispatcherServlet implements ServletContextListener{

	private ContextLoader contextLoader;

	/**
	 * Initialize the root web application context.
	 */
	public void contextInitialized(ServletContextEvent event) {
		this.contextLoader = createContextLoader();
		this.contextLoader.initWebApplicationContext(event.getServletContext());
		
		onFramework();
	}	

	/**
	 * Create the ContextLoader to use. Can be overridden in subclasses.
	 * @return the new ContextLoader
	 */
	protected ContextLoader createContextLoader() {
		return new ContextLoader();
	}

	/**
	 * Return the ContextLoader used by this listener.
	 * @return the current ContextLoader
	 */
	public ContextLoader getContextLoader() {
		return this.contextLoader;
	}

	/**
	 * Close the root web application context.
	 */
	public void contextDestroyed(ServletContextEvent event) {
		if (this.contextLoader != null) {
			this.contextLoader.closeWebApplicationContext(event.getServletContext());
		}
	}
	
	private void onFramework() {
		WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
		
		Map<?, ?> framworkEventListeners = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, 
				FramworkEventListener.class, true, false);
		
		if (framworkEventListeners != null) {
			Collection<?> values = framworkEventListeners.values();
			for (Object listener : values) {
				((FramworkEventListener) listener).onFramworkInit(context);
			}
		}
	}
}
